<?php
/**
 * ===============================================
 * 版权所有 2019-2050 青岛铁锤科技有限公司，并保留所有权利。
 * 网站地址: http://www.huaxianling.com
 * ===============================================
 * Author: Rag Hu
 * Created Time: 2019/7/1 9:36
 * Modified Time: 2019/7/1 9:36
 * Version: 2.0
 */

namespace App\Modules\MemberCard\Repositores;


use App\Exceptions\AllValidatorException;
use App\Exceptions\NotFoundException;
use App\Lib\Utilities;
use App\Models\MemberCard;
use App\Modules\MemberCard\Criterias\AppGetMemberCardListCriteria;
use App\Modules\MemberCard\Criterias\GetCenterCardFlowListCriteria;
use App\Modules\MemberCard\Validators\MemberCardValidator;
use Flower\Core\Repository\Eloquent\BaseRepository;
use Flower\Core\Repository\Exceptions\ValidatorException;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\MessageBag;

class MemberCardRepository extends BaseRepository
{
    public function model()
    {
        return MemberCard::class;
    }

    public function validator()
    {
        return MemberCardValidator::class;
    }


    public function statisticsMemberCard($request)
    {
        $res['total'] = $this->getTotalCards($request['store_id']);
        $date = isset($request['date']) ? $request['date'] : '';
        $userId = isset($request['user_id']) ? $request['user_id'] : 0;
        $res['today_list'] = $this->increaseCards($request['store_id'], $date, $userId);
        return $res;
    }

    /**
     * 计算某店铺所有会员卡数量
     * @param $storeId
     * @return mixed
     */
    protected function getTotalCards($storeId)
    {
        return $this->findWhere(['store_id' => $storeId])->count();
    }


    /**
     * 获取某店铺(或某理发师在某店)某天新增会员卡列表
     * @param $storeId
     * @param int $userId
     * @param int $date
     * @return array
     */
    public function increaseCards($storeId, $userId = 0, $date = 0)
    {
        $date = empty($date) ? date('Y-m-d', time()) : $date;
        $map = empty($userId) ? ['store_id' => $storeId] : ['store_id' => $storeId, 'user_id' => $userId];
        $list = $this->model->where($map)->whereDate('created_at', $date)->get()->toArray();
        return ['count' => count($list), 'list' => $list];
    }

    /**
     * 新增会员卡
     * @param $store_id
     * @param $type_id
     * @param $name
     * @param $mobile
     * @param $sex
     * @param $attribute
     * @param $count
     * @param $balance
     * @param $status
     * @param $user_id
     * @param $member_id
     * @param $num
     */
    public function createMemberCard($store_id, $type_id, $name, $mobile, $sex, $attribute, $count, $balance, $status, $user_id, $member_id, $num, $source)
    {
        $data = [
            'store_id' => $store_id,
            'type_id' => $type_id,
            'name' => $name,
            'mobile' => $mobile,
            'sex' => $sex,
            'attribute' => $attribute,
            // pc 和 手机端老会员转入进行不审核处理
            'status' => config('constant.orlMemberCardIsVerify') ? (($source == 2 || $source == 3) ? 1 : 0) : $status,
            'user_id' => $user_id,
            'member_id' => $member_id,
            'card_num' => $num,
            'source' => $source
        ];
        if ($attribute == 1) {
            $data['count'] = $count;
            $data['balance'] = $balance;
        } else {
            $data['balance'] = $balance;
        }

        return $this->create($data);
    }

    /**
     * 获取本店会员卡数量
     * @param $store_id
     * @param $status
     * @param $user_id
     * @return mixed
     */
    public function getStoreMemberCradNum($store_id, $status, $user_id)
    {
        $where = [];
        if ($user_id) {
            $where[] = ['user_id', '=', $user_id];
        }
        if ($status == 1 || $status == 0) {
            $where[] = ['status', '=', $status];
        }
        return $this->model->where('store_id', $store_id)
            ->where($where);

    }

    /**
     * 审核会员卡
     * @param $member_card_id
     * @param $operation
     */
    public function examineMemberCard($member_card_id, $operation, $user_id)
    {
        $data = [
            'status' => $operation,
            'user_id' => $user_id
        ];
        return $this->update($data,$member_card_id);
    }

    public function getMemberCardByNum($card_num)
    {
        $member_card = $this->model->where('card_mum', $card_num)->first();

        if (!$member_card) {
            throw new AllValidatorException(['msg' => '会员卡不存在']);
        }

        return $member_card;
    }

    /**
     * 会员卡扣款
     * @param $member_card_id
     * @param $amount
     * @return mixed
     */
    public function consumption($member_card_id, $amount)
    {
        $member_card = $this->model->find($member_card_id);

        $attribubute = $member_card->attribubute;

        if ($attribubute == 1) {
            $member_card->decrement('count', $amount);
        } else {
            $member_card->decrement('balance', $amount);
        }

        return $member_card;
    }

    /**
     * 充值
     * @param $member_card_id
     * @param $amount
     * @return mixed
     */
    public function recharge($member_card_id, $balance, $count = 0)
    {
        $member_card = $this->find($member_card_id);

        $member_card->increment('count', $count);
        $member_card->increment('balance', $balance);

        return $member_card;
    }

    /**
     *  查询次服务是否适用于本卡
     * @param $serviceId
     * @param $cardId
     * @return mixed
     * @throws AllValidatorException
     * @throws NotFoundException
     */
    public function isSuitableByServiceId($serviceIds, $cardId)
    {
        $res = $this->model->with(['cardType' => function ($v) use ($serviceIds) {
            $v->with(['cardTypeService' => function ($q) use ($serviceIds) {
                $q->whereIn('service_id',$serviceIds);
            }]);
        }])->find($cardId);

        if (empty($res)) {
            throw new NotFoundException(['msg' => '该会员卡不存在！']);
        }

        if (!isset($res->cardType->cardTypeService[0])) {
            throw new AllValidatorException(['msg' => '该卡的使用范围不包含此服务']);
        }
        return $res;
    }

    /**
     * 是否存在
     * @param $cardId
     * @return mixed
     * @throws NotFoundException
     */
    public function isExisted($cardId)
    {
        $cardInfo = $this->find($cardId);
        if (empty($cardInfo)) {
            throw new NotFoundException(['msg' => "对不起,您输入的会员卡数据未找到！"]);
        }
        return $cardInfo;
    }

    public function editTransferMemberCard($member_card_id, $card_type_id, $name, $mobile, $sex, $attribute, $count, $balance)
    {
        $update_data = [];

        if ($card_type_id) {
            $update_data['type_id'] = $card_type_id;
        }
        if ($name) {
            $update_data['name'] = $name;
        }

        if ($mobile) {
            $update_data['mobile'] = $mobile;
        }
        if ($sex) {
            $update_data['sex'] = $sex;
        }
        if ($attribute) {
            $update_data['attribute'] = $attribute;
        }
        if ($count) {
            $update_data['count'] = $count;
        }
        if ($balance) {
            $update_data['balance'] = $balance;
        }

        return $this->update($update_data, $member_card_id);

    }


    public function getAmountRate($storeId, $date, $compareDate)
    {
        // return $this->model
        //     ->selectRaw('date(created_at) as dates, count(id) as counts')
        //     ->whereRaw('(store_id=' . $storeId . ' and  date(created_at)="' . $date . '")')
        //     ->orWhereRaw('(store_id=' . $storeId . ' and date(created_at)="' . $compareDate . '")  and delete_at is null group by date(created_at)')
        //     ->get()->toArray();
        $sql = 'select date(created_at) as dates, count(id) as counts from `hx_member_card` where (store_id="'.$storeId.'" and  date(created_at)="'.$date.'") or (store_id="'.$storeId.'" and date(created_at)="'.$compareDate.'")  and deleted_at is null  group by date(created_at) ';
        $res =  DB::select($sql);
        if(!empty($res)){
            foreach ($res as $key => $value) {
                $list[] = [
                    'dates'=> $value->dates,
                    'counts'=> $value->counts
                ];
            }
            $res = $list;
        }
        return $res;
    }

    //获取理发师在某店某日办理的会员卡数
    public function getBarberDateMemberCardNum($user_id, $store_id, $date)
    {
        return $this->model->where('user_id', $user_id)
            ->where('store_id', $store_id)
            ->whereDate('created_at','=',$date)
            ->get()
            ->count();
    }

    /**
     * 统计会员卡数量
     * @param $storeId
     * @param $startDate
     * @param $endDate
     * @param bool $isNewAdd
     * @return mixed
     * @author Happy dong
     * @modifiedTime 2019-08-19 20:08
     */
    public function getMemberCardCount($storeId, $startDate, $endDate, $isNewAdd = true, $user_id = null)
    {
        $isAll = empty($startDate) && empty($endDate) ? false : true;
        return $this->model
            ->selectRaw('count(id) as card_count')
            ->when($isAll, function ($v) use ($startDate, $endDate) {
                $v->whereDate('created_at', '>=', $endDate)
                    ->whereDate('created_at', '<=', $startDate);
            })
            ->where('store_id', '=', $storeId)
            ->where('status','=',1)
//            ->when($isNewAdd, function ($v) {
//                $v->where('source', '=', 1);
//            })
            ->when($user_id, function ($query) use ($user_id) {
                $query->where('user_id', $user_id);
            })
            ->first();
    }

	/**
	 * 统计店铺的新增会员
	 * @param $storeId
	 * @param $dataList
	 * @return mixed
	 */
    public function increaseCountsByStoreAndDate($storeId,$dataList){
    	return $this->model->where(['store_id'=>$storeId,'status'=>1])->whereDate('created_at', '>=', $dataList['end_date'])
			    ->whereDate('created_at', '<=', $dataList['start_date'])->count();

    }





    /*
     * 店铺会员卡统计
     */
    public function getMemberCardNum($store_id, $card_type_id, $is_exhausted, $user_id = null)
    {
        return $this->model
            ->when($is_exhausted == 1, function ($query) {
                $query->where('count', 0)->where('balance', 0);
            })
            ->when($card_type_id, function ($query) use ($card_type_id) {
                $query->where('type_id', $card_type_id);
            })
            ->when($user_id, function ($query) use ($user_id) {
                $query->where('user_id', $user_id);
            })
            ->where('store_id', $store_id)
            ->where('status', 1)
            ->get()
            ->count();
    }

    /*
     * 店铺老会员统计
     */
    public function getOldMemberCardNum($store_id, $is_today)
    {
        return $this->model
            ->when($is_today == 1, function ($query) {
                $query->whereRaw('to_days(created_at) = to_days(now())');
            })
            ->where('store_id', $store_id)
            ->where(function ($query) {
                $query->where('source', 2)->orWhere('source', 3);
            })
            ->get()
            ->count();
    }

    public function getMemberCardApplyNum($store_id, $is_today = 0)
    {
        return $this->model
            ->when($is_today == 1, function ($query) {
                $query->whereRaw('TO_DAYS(now()) = TO_DAYS(created_at)');
            })
            ->where(function ($query) {
                $query->where('source', 1)->orWhere('source', 4);
            })
            ->where('store_id', $store_id)
            ->count();
    }

    /**
     * 领取会员卡
     * @param $member_id
     * @param $member_card_id
     * @return mixed
     */
    public function receiveMemberCard($member_id, $member_card_id)
    {
        $data = [
            'member_id' => $member_id,
            'status' => 1
        ];
        return $this->update($data, $member_card_id);
    }

    public function getCardTypeCount($card_type_id)
    {
        return $this->model->where('type_id', $card_type_id)->count();
    }

    public static function getMemberCardName($memberId){
		return empty($memberId) ? [] : MemberCard::getMemberCardNameById($memberId);
    }
}
